package sample.Koans

/**
 * Created by runjia on 17-6-2.
 */
fun task(): List<Boolean> {
    val isEven: Int.() -> Boolean = { this % 2 == 0 }
    val isOdd: Int.() -> Boolean = { this % 2 == 1 }

    fun Int.odd(): Boolean = this % 2 == 1

    return listOf(42.isOdd(), 239.isOdd(), 294823098.isEven())
}

fun <K, V>buildMap(builderAction: HashMap<K, V>.() -> Unit): Map<K, V> {
    val map = HashMap<K, V>()
    map.builderAction()
    return map
}

fun usage(): Map<Int, String> {
    return buildMap {
        put(0, "0")
        for (i in 1..10) {
            put(i, "$i")
        }
    }
}

fun main(args:Array<String>) {
    println( usage() )

    println("123".length2)
}

fun <T> T.myApply(f: T.() -> Unit): T {
    this.apply(f)
    return this
}
fun <T> T.myInvoke(f: (T) -> Unit): T {
    f.invoke(this)
    return this
}

fun createString(): String {
    return StringBuilder().myApply {
        append("Numbers: ")
        for (i in 1..10) {
            append(i)
        }
    }.toString()
}

fun createMap(): Map<Int, String> {
    return hashMapOf<Int, String>().myApply {
        put(0, "0")
        for (i in 1..10) {
            put(i, "$i")
        }
    }
}

// Extensions are resolved statically: you cannot shadow a member function with an extension
val String.length2:Int get() = this.length * 2